﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace hutil {
    /**
   *┌────────────────────────────────────────────────┐
   *│　描    述：ObjectConvert                                                    
   *│　作    者：sgj                                              
   *│　版    本：1.0                                              
   *│　创建时间：2022-06-25 08:23:00                        
   *└────────────────────────────────────────────────┘
   **/
    public class ObjectConvert {
    public   T jsonConvert<T>( String value) {

            JObject jsonObject = JsonConvert.DeserializeObject<JObject>(value);
         
            if( jsonObject == null ) {
                return default(T);
            }



            Type type = typeof(T);
            T t = ( T ) Activator.CreateInstance(type);
            FieldInfo[] fields= type.GetFields();
            foreach( FieldInfo f in fields ) {
                MappingNameAttribute mappingName =   f.GetCustomAttribute<MappingNameAttribute>();
                JToken jt = getData(jsonObject ,mappingName);
                f.SetValue(t ,jt);

            }
            return t;
        }

        JToken getData(JObject jsonObject ,MappingNameAttribute mappingName) {
            String[] names = mappingName.getNames();
            foreach( String n in names ) {
                if( jsonObject.ContainsKey(n) ) {
                    return jsonObject[n];
                }
            }
            return null;

        }
    }
}
